package com.sheng.project.demo.utils;

import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;
import java.util.Locale;

@Slf4j
public class SHAUtilV2 {
    /**
     * 算法常量： SHA1
     */
    public static final String ALGORITHM_SHA1 = "SHA-1";
    /**
     * 算法常量： SHA256
     */
    public static final String ALGORITHM_SHA256 = "SHA-256";

    /**
     * sha1计算.
     *
     * @param data     待计算的数据
     * @param encoding 编码
     * @return 计算结果
     */
    public byte[] sha1(String data, String encoding) {
        try {
            MessageDigest md = MessageDigest.getInstance(ALGORITHM_SHA1);
            md.reset();
            md.update(data.getBytes(encoding));
            return md.digest();
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new IllegalArgumentException("SHA-1计算失败");
    }

    /**
     * sha256计算.
     *
     * @param data     待计算的数据
     * @param encoding 编码
     * @return 计算结果
     */
    public byte[] sha256(String data, String encoding) {
        try {
            MessageDigest md = MessageDigest.getInstance(ALGORITHM_SHA256);
            md.reset();
            md.update(data.getBytes(encoding));
            return md.digest();
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new IllegalArgumentException("SHA-256计算失败");
    }

    /**
     * sha转string
     *
     * @param digest
     * @return
     */
    public String byte2String(byte[] digest) {
        String str = "";
        String tempStr = "";
        for (int i = 0; i < digest.length; i++) {
            tempStr = (Integer.toHexString(digest[i] & 0xff));
            if (tempStr.length() == 1) {
                str = str + "0" + tempStr;
            } else {
                str = str + tempStr;
            }
        }
        return str.toLowerCase(Locale.ENGLISH);
    }

}
